package com.dbutils;

import com.dbutils.dao.AccountDAO;
import com.dbutils.entity.Account;
import com.dbutils.utils.JdbcKit;

import java.math.BigDecimal;

public class AccountService {

    /**
     * 转账方法
     *
     * @param fromID 原始账户
     * @param toID   目标账户
     * @param money  转入多少钱
     */

    public void trafferAccount(int fromID, int toID, BigDecimal money) {
        try {
            JdbcKit.startTransaction();
            AccountDAO dao = new AccountDAO();
            Account from = dao.findAccount(fromID);
            Account to = dao.findAccount(toID);
            from.setMoney(from.getMoney().subtract(money));
            to.setMoney(to.getMoney().add(money));
            dao.updateAccount(from);
            dao.updateAccount(to);
            JdbcKit.commit();
        } catch (Exception e) {
            JdbcKit.rollback();
            throw new RuntimeException();
        } finally {
            JdbcKit.close();
        }
    }
}
